package com.study.talk.ui.app.group.create.fragment

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import com.study.talk.ui.app.base.BaseFragment
import com.study.talk.databinding.FragmentCreateGroupInfoBinding
import com.study.talk.utils.FileUtil
import com.study.talk.R
import com.study.talk.ui.app.group.create.CreateGroupViewModel
import com.study.talk.utils.extras.showToast
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class CreateGroupInfoFragment : BaseFragment() {

    private lateinit var binding: FragmentCreateGroupInfoBinding

    private val parentViewModel by lazy { ViewModelProvider(requireActivity())[CreateGroupViewModel::class] }

    private val selectPhoto: ActivityResultLauncher<PickVisualMediaRequest> =
        registerForActivityResult(
            ActivityResultContracts.PickVisualMedia()
        ) { uri: Uri? ->
            uri?.let { vm.uploads(FileUtil.getPathFromUri(requireContext(), it)) }
        }

    private val takePhoto: ActivityResultLauncher<Uri> =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { result: Boolean ->
            if (result) {
                uri?.let { vm.uploads(FileUtil.getPathFromUri(requireContext(), it)) }
            }
        }

    private val vm: CreateGroupInfoViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_create_group_info, container, false)
        initView()
        return binding.root
    }

    private fun initView() {

        binding.vm = vm
        binding.lifecycleOwner = this

        binding.createGroupBt.setOnClickListener {
            if (parentViewModel.selectUsers.value.isNullOrEmpty()) {
                showToast("没有选择任何好友欸")
                return@setOnClickListener
            }
            parentViewModel.selectUsers.value?.let {
                vm.submit(mainUser = app.localUserId, users = it)
            }
        }
        binding.createGroupImg.setOnClickListener {
            showSelectPhotoDialog(
                selectPhoto, takePhoto
            )
        }
    }

}